package main

import (
	"fmt"
	"log"
	"time"

	"simple-crm/config"
	"simple-crm/models"

	"gorm.io/gorm"
)

// 简化的Permission结构体，只包含实际存在的字段
type SimplePermission struct {
	ID          uint   `gorm:"primaryKey"`
	PID         uint   `gorm:"column:pid;default:0"`
	Name        string `gorm:"size:100;not null"`
	DisplayName string `gorm:"size:100;not null"`
	Resource    string `gorm:"size:50"`
	Action      string `gorm:"size:50"`
	Description string `gorm:"type:text"`
	Sort        int    `gorm:"default:0"`
	IsGroup     bool   `gorm:"default:false"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

func (SimplePermission) TableName() string {
	return "permissions"
}

// PermissionGroup 权限分组定义
type PermissionGroup struct {
	Name        string
	DisplayName string
	Description string
	Sort        int
	Permissions []PermissionItem
}

// PermissionItem 权限项定义
type PermissionItem struct {
	Name        string
	DisplayName string
	Resource    string
	Action      string
	Description string
	Sort        int
}

// RolePermissionMapping 角色权限映射
type RolePermissionMapping struct {
	RoleName    string
	DisplayName string
	Description string
	Permissions []string // 权限名称列表
}

func main() {
	// 加载配置
	cfg := config.Load()

	// 初始化数据库连接
	db := config.InitDB(cfg)

	fmt.Println("开始生成权限测试数据...")

	// 清空现有权限数据
	if err := clearExistingData(db); err != nil {
		log.Fatal("清空现有数据失败:", err)
	}

	// 生成权限分组和权限
	if err := generatePermissions(db); err != nil {
		log.Fatal("生成权限数据失败:", err)
	}

	// 生成角色
	if err := generateRoles(db); err != nil {
		log.Fatal("生成角色数据失败:", err)
	}

	// 分配角色权限
	if err := assignRolePermissions(db); err != nil {
		log.Fatal("分配角色权限失败:", err)
	}

	// 显示统计信息
	showStatistics(db)

	fmt.Println("权限测试数据生成完成！")
}

// clearExistingData 清理现有数据
func clearExistingData(db *gorm.DB) error {
	fmt.Println("清理现有数据...")

	// 清理角色权限关联
	if err := db.Exec("DELETE FROM role_permissions").Error; err != nil {
		return fmt.Errorf("清理角色权限关联失败: %v", err)
	}

	// 清理权限数据
	if err := db.Exec("DELETE FROM permissions").Error; err != nil {
		return fmt.Errorf("清理权限数据失败: %v", err)
	}

	// 清理角色数据
	if err := db.Exec("DELETE FROM roles").Error; err != nil {
		return fmt.Errorf("清理角色数据失败: %v", err)
	}

	// 重置自增ID
	if err := db.Exec("ALTER TABLE permissions AUTO_INCREMENT = 1").Error; err != nil {
		return fmt.Errorf("重置权限表自增ID失败: %v", err)
	}

	if err := db.Exec("ALTER TABLE roles AUTO_INCREMENT = 1").Error; err != nil {
		return fmt.Errorf("重置角色表自增ID失败: %v", err)
	}

	return nil
}

// generatePermissions 生成权限数据
func generatePermissions(db *gorm.DB) error {
	fmt.Println("生成权限分组和权限...")

	// 定义权限分组和权限
	permissionGroups := []PermissionGroup{
		{
			Name:        "system",
			DisplayName: "系统管理",
			Description: "系统核心功能管理",
			Sort:        1,
			Permissions: []PermissionItem{
				{"system.user.view", "用户查看", "user", "view", "查看系统用户列表", 1},
				{"system.user.create", "用户创建", "user", "create", "创建新系统用户", 2},
				{"system.user.update", "用户编辑", "user", "update", "编辑系统用户信息", 3},
				{"system.user.delete", "用户删除", "user", "delete", "删除系统用户", 4},
				{"system.role.view", "角色查看", "role", "view", "查看角色列表", 5},
				{"system.role.create", "角色创建", "role", "create", "创建新角色", 6},
				{"system.role.update", "角色编辑", "role", "update", "编辑角色信息", 7},
				{"system.role.delete", "角色删除", "role", "delete", "删除角色", 8},
				{"permission.view", "权限查看", "permission", "view", "查看权限列表", 9},
				{"permission.create", "权限创建", "permission", "create", "创建新权限", 10},
				{"permission.update", "权限编辑", "permission", "update", "编辑权限信息", 11},
				{"permission.delete", "权限删除", "permission", "delete", "删除权限", 12},
				{"system.log.view", "操作日志", "log", "view", "查看系统操作日志", 13},
				{"system.config.view", "系统配置查看", "config", "view", "查看系统配置", 14},
				{"system.config.update", "系统配置修改", "config", "update", "修改系统配置", 15},
			},
		},
		{
			Name:        "customer",
			DisplayName: "客户管理",
			Description: "客户信息管理功能",
			Sort:        2,
			Permissions: []PermissionItem{
				{"customer.view", "客户查看", "customer", "view", "查看客户信息", 1},
				{"customer.create", "客户创建", "customer", "create", "创建新客户", 2},
				{"customer.update", "客户编辑", "customer", "update", "编辑客户信息", 3},
				{"customer.delete", "客户删除", "customer", "delete", "删除客户", 4},
				{"customer.import", "客户导入", "customer", "import", "批量导入客户", 5},
				{"customer.export", "客户导出", "customer", "export", "导出客户数据", 6},
				{"customer.assign", "客户分配", "customer", "assign", "分配客户给销售", 7},
				{"customer.follow", "客户跟进", "customer", "follow", "客户跟进记录", 8},
				{"customer.tag", "客户标签", "customer", "tag", "管理客户标签", 9},
				{"customer.merge", "客户合并", "customer", "merge", "合并重复客户", 10},
			},
		},
		{
			Name:        "partner",
			DisplayName: "合作机构",
			Description: "合作机构管理功能",
			Sort:        3,
			Permissions: []PermissionItem{
				{"partner.view", "机构查看", "partner", "view", "查看合作机构信息", 1},
				{"partner.create", "机构创建", "partner", "create", "创建新合作机构", 2},
				{"partner.update", "机构编辑", "partner", "update", "编辑合作机构信息", 3},
				{"partner.delete", "机构删除", "partner", "delete", "删除合作机构", 4},
				{"partner.approve", "机构审核", "partner", "approve", "审核合作机构申请", 5},
				{"partner.contract", "合同管理", "partner", "contract", "管理合作合同", 6},
				{"partner.settlement", "结算管理", "partner", "settlement", "管理合作结算", 7},
			},
		},
		{
			Name:        "push",
			DisplayName: "推送管理",
			Description: "推送相关功能管理",
			Sort:        4,
			Permissions: []PermissionItem{
				{"push.view", "推送查看", "push", "view", "查看推送记录", 1},
				{"push.smart", "智能推送", "push", "smart", "执行智能推送", 2},
				{"push.manual", "手动推送", "push", "manual", "执行手动推送", 3},
				{"push.batch", "批量推送", "push", "batch", "执行批量推送", 4},
				{"push.retry", "重试推送", "push", "retry", "重试失败的推送", 5},
				{"push.stats", "推送统计", "push", "stats", "查看推送统计数据", 6},
				{"push.template", "推送模板", "push", "template", "管理推送模板", 7},
				{"push.schedule", "定时推送", "push", "schedule", "设置定时推送任务", 8},
			},
		},
		{
			Name:        "finance",
			DisplayName: "财务管理",
			Description: "财务相关功能管理",
			Sort:        5,
			Permissions: []PermissionItem{
				{"finance.order.view", "订单查看", "order", "view", "查看订单信息", 1},
				{"finance.order.create", "订单创建", "order", "create", "创建新订单", 2},
				{"finance.order.update", "订单编辑", "order", "update", "编辑订单信息", 3},
				{"finance.payment.view", "支付查看", "payment", "view", "查看支付记录", 4},
				{"finance.payment.process", "支付处理", "payment", "process", "处理支付事务", 5},
				{"finance.refund.view", "退款查看", "refund", "view", "查看退款记录", 6},
				{"finance.refund.process", "退款处理", "refund", "process", "处理退款申请", 7},
				{"finance.invoice.view", "发票查看", "invoice", "view", "查看发票信息", 8},
				{"finance.invoice.create", "发票开具", "invoice", "create", "开具发票", 9},
			},
		},
		{
			Name:        "report",
			DisplayName: "报表统计",
			Description: "数据报表和统计功能",
			Sort:        6,
			Permissions: []PermissionItem{
				{"report.sales.view", "销售报表", "report", "sales", "查看销售数据报表", 1},
				{"report.customer.view", "客户报表", "report", "customer", "查看客户数据报表", 2},
				{"report.finance.view", "财务报表", "report", "finance", "查看财务数据报表", 3},
				{"report.partner.view", "机构报表", "report", "partner", "查看机构数据报表", 4},
				{"report.push.view", "推送报表", "report", "push", "查看推送数据报表", 5},
				{"report.export", "报表导出", "report", "export", "导出报表数据", 6},
				{"report.custom", "自定义报表", "report", "custom", "创建自定义报表", 7},
			},
		},
		{
			Name:        "marketing",
			DisplayName: "营销管理",
			Description: "营销活动和推广功能",
			Sort:        7,
			Permissions: []PermissionItem{
				{"marketing.campaign.view", "活动查看", "campaign", "view", "查看营销活动", 1},
				{"marketing.campaign.create", "活动创建", "campaign", "create", "创建营销活动", 2},
				{"marketing.campaign.update", "活动编辑", "campaign", "update", "编辑营销活动", 3},
				{"marketing.campaign.delete", "活动删除", "campaign", "delete", "删除营销活动", 4},
				{"marketing.coupon.view", "优惠券查看", "coupon", "view", "查看优惠券", 5},
				{"marketing.coupon.create", "优惠券创建", "coupon", "create", "创建优惠券", 6},
				{"marketing.email.send", "邮件营销", "email", "send", "发送营销邮件", 7},
				{"marketing.sms.send", "短信营销", "sms", "send", "发送营销短信", 8},
			},
		},
		{
			Name:        "content",
			DisplayName: "内容管理",
			Description: "内容发布和管理功能",
			Sort:        8,
			Permissions: []PermissionItem{
				{"content.article.view", "文章查看", "article", "view", "查看文章内容", 1},
				{"content.article.create", "文章创建", "article", "create", "创建新文章", 2},
				{"content.article.update", "文章编辑", "article", "update", "编辑文章内容", 3},
				{"content.article.delete", "文章删除", "article", "delete", "删除文章", 4},
				{"content.article.publish", "文章发布", "article", "publish", "发布文章", 5},
				{"content.media.upload", "媒体上传", "media", "upload", "上传媒体文件", 6},
				{"content.media.manage", "媒体管理", "media", "manage", "管理媒体文件", 7},
				{"content.category.manage", "分类管理", "category", "manage", "管理内容分类", 8},
			},
		},
	}

	// 创建权限分组和权限
	for _, group := range permissionGroups {
		// 创建权限分组
		permissionGroup := SimplePermission{
			PID:         0,
			Name:        group.Name,
			DisplayName: group.DisplayName,
			Description: group.Description,
			Sort:        group.Sort,
			IsGroup:     true,
			CreatedAt:   time.Now(),
			UpdatedAt:   time.Now(),
		}

		if err := db.Create(&permissionGroup).Error; err != nil {
			return fmt.Errorf("创建权限分组 %s 失败: %v", group.Name, err)
		}

		fmt.Printf("创建权限分组: %s (ID: %d)\n", group.DisplayName, permissionGroup.ID)

		// 创建该分组下的具体权限
		for _, perm := range group.Permissions {
			permission := SimplePermission{
				PID:         permissionGroup.ID,
				Name:        perm.Name,
				DisplayName: perm.DisplayName,
				Resource:    perm.Resource,
				Action:      perm.Action,
				Description: perm.Description,
				Sort:        perm.Sort,
				IsGroup:     false,
				CreatedAt:   time.Now(),
				UpdatedAt:   time.Now(),
			}

			if err := db.Create(&permission).Error; err != nil {
				return fmt.Errorf("创建权限 %s 失败: %v", perm.Name, err)
			}

			fmt.Printf("  - 创建权限: %s\n", perm.DisplayName)
		}
	}

	return nil
}

// generateRoles 生成角色数据
func generateRoles(db *gorm.DB) error {
	fmt.Println("生成角色数据...")

	roles := []models.Role{
		{Name: "super_admin", DisplayName: "超级管理员", Description: "拥有所有权限的超级管理员"},
		{Name: "admin", DisplayName: "系统管理员", Description: "系统管理相关权限"},
		{Name: "sales_manager", DisplayName: "销售经理", Description: "客户和销售管理权限"},
		{Name: "sales", DisplayName: "销售员", Description: "基础客户管理权限"},
		{Name: "finance_manager", DisplayName: "财务经理", Description: "财务管理权限"},
		{Name: "marketing_manager", DisplayName: "营销经理", Description: "营销活动管理权限"},
		{Name: "content_editor", DisplayName: "内容编辑", Description: "内容管理权限"},
		{Name: "viewer", DisplayName: "查看者", Description: "只读权限"},
	}

	for _, role := range roles {
		role.CreatedAt = time.Now()
		role.UpdatedAt = time.Now()

		if err := db.Create(&role).Error; err != nil {
			return fmt.Errorf("创建角色 %s 失败: %v", role.Name, err)
		}

		fmt.Printf("创建角色: %s\n", role.DisplayName)
	}

	return nil
}

// assignRolePermissions 分配角色权限
func assignRolePermissions(db *gorm.DB) error {
	fmt.Println("分配角色权限...")

	// 定义角色权限映射
	rolePermissions := []RolePermissionMapping{
		{
			RoleName:    "super_admin",
			DisplayName: "超级管理员",
			Description: "所有权限",
			Permissions: []string{"*"}, // 特殊标记，表示所有权限
		},
		{
			RoleName:    "admin",
			DisplayName: "系统管理员",
			Description: "系统管理权限",
			Permissions: []string{
				"system.user.view", "system.user.create", "system.user.update", "system.user.delete",
				"system.role.view", "system.role.create", "system.role.update", "system.role.delete",
				"permission.view", "permission.create", "permission.update", "permission.delete",
				"system.log.view", "system.config.view", "system.config.update",
			},
		},
		{
			RoleName:    "sales_manager",
			DisplayName: "销售经理",
			Description: "客户管理和报表权限",
			Permissions: []string{
				"customer.view", "customer.create", "customer.update", "customer.delete",
				"customer.import", "customer.export", "customer.assign", "customer.follow",
				"customer.tag", "customer.merge",
				"report.sales.view", "report.customer.view", "report.export",
			},
		},
		{
			RoleName:    "sales",
			DisplayName: "销售员",
			Description: "基础客户管理权限",
			Permissions: []string{
				"customer.view", "customer.create", "customer.update", "customer.follow",
			},
		},
		{
			RoleName:    "finance_manager",
			DisplayName: "财务经理",
			Description: "财务管理权限",
			Permissions: []string{
				"finance.order.view", "finance.order.create", "finance.order.update",
				"finance.payment.view", "finance.payment.process",
				"finance.refund.view", "finance.refund.process",
				"finance.invoice.view", "finance.invoice.create",
				"report.finance.view", "report.export",
			},
		},
		{
			RoleName:    "marketing_manager",
			DisplayName: "营销经理",
			Description: "营销管理权限",
			Permissions: []string{
				"marketing.campaign.view", "marketing.campaign.create", "marketing.campaign.update", "marketing.campaign.delete",
				"marketing.coupon.view", "marketing.coupon.create",
				"marketing.email.send", "marketing.sms.send",
				"customer.view", "customer.tag",
			},
		},
		{
			RoleName:    "content_editor",
			DisplayName: "内容编辑",
			Description: "内容管理权限",
			Permissions: []string{
				"content.article.view", "content.article.create", "content.article.update", "content.article.delete",
				"content.article.publish", "content.media.upload", "content.media.manage",
				"content.category.manage",
			},
		},
		{
			RoleName:    "viewer",
			DisplayName: "查看者",
			Description: "只读权限",
			Permissions: []string{
				"customer.view", "partner.view", "push.view", "push.stats",
				"finance.order.view", "finance.payment.view", "finance.refund.view", "finance.invoice.view",
				"report.sales.view", "report.customer.view", "report.finance.view", "report.partner.view", "report.push.view",
				"marketing.campaign.view", "marketing.coupon.view",
				"content.article.view",
			},
		},
	}

	// 为每个角色分配权限
	for _, roleMapping := range rolePermissions {
		// 获取角色
		var role models.Role
		if err := db.Where("name = ?", roleMapping.RoleName).First(&role).Error; err != nil {
			return fmt.Errorf("获取角色 %s 失败: %v", roleMapping.RoleName, err)
		}

		fmt.Printf("为角色 %s 分配权限...\n", roleMapping.DisplayName)

		if len(roleMapping.Permissions) == 1 && roleMapping.Permissions[0] == "*" {
			// 超级管理员：分配所有权限
			var permissions []SimplePermission
			if err := db.Where("is_group = ?", false).Find(&permissions).Error; err != nil {
				return fmt.Errorf("获取所有权限失败: %v", err)
			}

			for _, permission := range permissions {
				rolePermission := models.RolePermission{
					RoleID:       role.ID,
					PermissionID: permission.ID,
					CreatedAt:    time.Now(),
				}

				if err := db.Create(&rolePermission).Error; err != nil {
					return fmt.Errorf("分配权限失败: %v", err)
				}
			}

			fmt.Printf("  - 分配了 %d 个权限\n", len(permissions))
		} else {
			// 其他角色：分配指定权限
			for _, permName := range roleMapping.Permissions {
				var permission SimplePermission
				if err := db.Where("name = ? AND is_group = ?", permName, false).First(&permission).Error; err != nil {
					fmt.Printf("  - 警告：权限 %s 不存在，跳过\n", permName)
					continue
				}

				rolePermission := models.RolePermission{
					RoleID:       role.ID,
					PermissionID: permission.ID,
					CreatedAt:    time.Now(),
				}

				if err := db.Create(&rolePermission).Error; err != nil {
					return fmt.Errorf("分配权限 %s 给角色 %s 失败: %v", permName, roleMapping.RoleName, err)
				}

				fmt.Printf("  - 分配权限: %s\n", permission.DisplayName)
			}
		}
	}

	return nil
}

// showStatistics 显示统计信息
func showStatistics(db *gorm.DB) {
	fmt.Println("\n=== 权限测试数据统计 ===")

	// 权限分组数量
	var groupCount int64
	db.Model(&SimplePermission{}).Where("is_group = ?", true).Count(&groupCount)
	fmt.Printf("权限分组数量: %d\n", groupCount)

	// 具体权限数量
	var permissionCount int64
	db.Model(&SimplePermission{}).Where("is_group = ?", false).Count(&permissionCount)
	fmt.Printf("具体权限数量: %d\n", permissionCount)

	// 角色数量
	var roleCount int64
	db.Model(&models.Role{}).Count(&roleCount)
	fmt.Printf("角色数量: %d\n", roleCount)

	// 角色权限关联数量
	var rolePermissionCount int64
	db.Model(&models.RolePermission{}).Count(&rolePermissionCount)
	fmt.Printf("角色权限关联数量: %d\n", rolePermissionCount)

	fmt.Println("\n=== 权限分组详情 ===")

	// 显示每个分组的权限数量
	var groups []SimplePermission
	db.Where("is_group = ?", true).Order("sort").Find(&groups)

	for _, group := range groups {
		var count int64
		db.Model(&SimplePermission{}).Where("pid = ? AND is_group = ?", group.ID, false).Count(&count)
		fmt.Printf("%s: %d 个权限\n", group.DisplayName, count)
	}
}
